<?php
session_start();
include("../../service/categoryService.php");

$proId = $_POST["proId"];
$quantity = $_POST["quantity"];
$newOptionItems = isset($_POST["optionItem"]) ? $_POST["optionItem"] : array();
$cart = null;
$count = 0;

// init cart
if(isset($_SESSION['cart'])) {
    $cart = $_SESSION["cart"];
    //$data = array(); // 0: product id, 1: number of product, 2: options
    //$options = array(); // 0: option item id 
} else {
    $cart = array();
}

// add products from pages that are not product detail page
if(!is_array($newOptionItems)){
    $newOptionItems = array();
    $oldOptionItems = getOptionInfo($proId);
    
    while($row = mysql_fetch_array($oldOptionItems)){
        $newOptionItems[] = $row["OOI_ID"];
    }
}

// check that new added product with the same options is in the cart or not 
for($i = 0; $i < count($cart);$i++){
    if($cart[$i][0] == $proId){
        if(count(array_diff_assoc($cart[$i][2], $newOptionItems)) == 0){
            $cart[$i][1] += $quantity;
            $count++;
            break;
        }     
    }
}

if($count == 0){
    $data = array();
    $data[0] = $proId;
    $data[1] = $quantity;
    $data[2] = $newOptionItems;
    array_push($cart, $data);
}

// add product to empty cart
if(count($cart) == 0){
    $data = array();
    $data[0] = $proId;
    $data[1] = $quantity;
    $data[2] = $newOptionItems;
    array_push($cart, $data);
}

$_SESSION["cart"] = $cart;
echo count($_SESSION["cart"]);
?>